<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="90px"
    >
      <el-form-item label="数据源名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入数据源名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据源类型" prop="type">
        <el-select v-model="queryParams.type" class="!w-240px" clearable placeholder="请选择类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ETL_DATASOURCE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openDatasourceSelect()"
          v-hasPermi="['system:post:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['system:post:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column label="数据源名称" align="center" prop="name" />
      <el-table-column label="主机" align="center" prop="ip" />
      <el-table-column label="端口" align="center" prop="port" />
      <el-table-column label="数据库名" align="center" prop="dbname" />
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="密码" align="center" prop="password" />
      <el-table-column label="数据源类型" align="center" prop="type" />
<!--      <el-table-column label="数据源类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ETL_DATASOURCE_TYPE" :value="scope.row.type" />
        </template>
      </el-table-column>-->
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
        :formatter="dateFormatter"
      />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDatasourceForm('update', scope.row.type,scope.row.id)"
            v-hasPermi="['system:post:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['system:post:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
  <!-- 表单弹窗：添加/修改-->
  <DatasourceSelect ref="refDatasourceSelect"  @datasource-selected="openDatasourceForm" />
  <!-- 使用 Suspense 确保动态组件加载完成 -->
  <Suspense>
    <!--根据已选择数据源，动态加载数据源配置项-->
    <component :is="currentDataSource"   ref="refCurrentDataSource" :dataSourceType="dataSourceType"/>
  </Suspense>

</template>
<script lang="ts" setup>
import{onMounted,provide} from 'vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import * as PostApi from '@/api/etl/datasource'
import DatasourceSelect from './DatasourceSelect.vue'
import PostgreSQL from './component/PostgreSQL.vue'
import MySQL from './component/MySQL.vue'
import { EtlDatasourceEnum } from '@/utils/constants'

defineOptions({ name: 'EtlDatasource' })


const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: '',
  name: '',
  status: undefined
})

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/*数据源配置框相关参数*/
const  dataSourceType=ref('');
/**添加操作 */
const refDatasourceSelect=ref()

/*动态展示数据源*/
const currentDataSource = ref(null);
// 使用 ref 创建子组件实例的引用
const refCurrentDataSource = ref(null);

/** 查询数据源列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PostApi.getPostPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

// 提供一个方法，用于在子组件中调用，当子组件修改，新增保存成功后，父窗口重新加载数据
provide('onSaveSuccess', getList);

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
/*打开选择数据源窗口*/
const openDatasourceSelect = () => {
  refDatasourceSelect.value.open()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await PostApi.deletePost(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await PostApi.exportPost(queryParams)
    download.excel(data, '数据源列表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
/*数据源已选择*/
const openDatasourceForm = (type: string, datasourceType ,id?: number) => {
  console.log(type,datasourceType,id)
  dataSourceType.value=datasourceType;
  switch (datasourceType) {
    case 'PostgreSQL':
      currentDataSource.value = PostgreSQL;
      setTimeout(() => {
          refCurrentDataSource.value.open(type,id);
      }, 100); // 100毫秒的延迟
      break;
    case 'MySQL':
      currentDataSource.value = MySQL;
      setTimeout(() => {
          refCurrentDataSource.value.open(type,id);
      }, 100); // 100毫秒的延迟
      break;
    default:
      currentDataSource.value = null;
  }
};

/** 初始化 **/
onMounted(() => {
  getList();
})

</script>
<style scoped>

</style>
